package com.yuda.campsite.controller;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.util.ZipUtil;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.yuda.campsite.domain.StudentInfo;
import com.yuda.campsite.service.impl.StudentInfoServiceImpl;
import com.yuda.common.core.utils.file.OssFileUtils;
import io.netty.buffer.ByteBufInputStream;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import com.yuda.common.log.annotation.Log;
import com.yuda.common.log.enums.BusinessType;
import com.yuda.common.security.annotation.PreAuthorize;
import com.yuda.campsite.domain.CampsiteWorkTeacher;
import com.yuda.campsite.service.ICampsiteWorkTeacherService;
import com.yuda.common.core.web.controller.BaseController;
import com.yuda.common.core.web.domain.AjaxResult;
import com.yuda.common.core.utils.poi.ExcelUtil;
import com.yuda.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 【请填写功能名称】Controller
 *
 * @author wyn
 * @date 2021-12-06
 */
@RestController
@RequestMapping("/teacher")
@Slf4j
public class CampsiteWorkTeacherController extends BaseController {
    @Autowired
    private ICampsiteWorkTeacherService campsiteWorkTeacherService;

//    @Qualifier(value = "ossClientOuter")
//    @Autowired
//    private OSS ossClientOuter;

    @Qualifier(value = "ossClientInter")
    @Autowired
    private OSS ossClientInter;
    @Resource
    private StudentInfoServiceImpl studentInfoService;

    public static boolean checkFileSize(long len, int size, String unit) {

        double fileSize = 0;
        if ("B".equals(unit.toUpperCase())) {
            fileSize = (double) len;
        } else if ("K".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1024;
        } else if ("M".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1048576;
        } else if ("G".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1073741824;
        }
        if (fileSize > size) {
            return false;
        }
        return true;
    }

    /**
     * 查询【请填写功能名称】列表
     */
    //   @PreAuthorize(hasPermi = "common:teacher:list")
    @GetMapping("/list")
    public TableDataInfo list(CampsiteWorkTeacher campsiteWorkTeacher) {
        startPage();
        List<CampsiteWorkTeacher> list = campsiteWorkTeacherService.selectCampsiteWorkTeacherList(campsiteWorkTeacher);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize(hasPermi = "common:teacher:export")
    @Log(title = "导出作业", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CampsiteWorkTeacher campsiteWorkTeacher) throws IOException {
        List<CampsiteWorkTeacher> list = campsiteWorkTeacherService.selectCampsiteWorkTeacherList(campsiteWorkTeacher);
        ExcelUtil<CampsiteWorkTeacher> util = new ExcelUtil<CampsiteWorkTeacher>(CampsiteWorkTeacher.class);
        util.exportExcel(response, list, "teacher");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    //  @PreAuthorize(hasPermi = "common:teacher:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        long l = Long.parseLong(id);
        return AjaxResult.success(campsiteWorkTeacherService.selectCampsiteWorkTeacherById(l));
    }

    /**
     * 新增【请填写功能名称】
     */
    // @PreAuthorize(hasPermi = "campsite:teacher:add")
    @Log(title = "新增作业", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Valid @RequestBody CampsiteWorkTeacher campsiteWorkTeacher) {
        List<String> stringList = campsiteWorkTeacherService.ChaXunZuoYe(campsiteWorkTeacher.getCampId());
        if (stringList != null) {
            for (String s : stringList) {
                if (s.equals(campsiteWorkTeacher.getWorkName())) {
                    return AjaxResult.error("作业名称不能重复");
                }
            }
        }
        /**设置创建时间就是第一次加入的时间*/
        Date date = new Date(System.currentTimeMillis());
        campsiteWorkTeacher.setCreateTime(date);
        /**查询此时营地中有几个作业(去掉删除的作业)*/
        Integer integer = campsiteWorkTeacherService.ZuoYeNum(String.valueOf(campsiteWorkTeacher.getCampId()));
        /**将下次新建的作业中的stu_work_num属性设置为加1*/
        campsiteWorkTeacher.setWorkNum(Long.valueOf(integer + 1));
        return toAjax(campsiteWorkTeacherService.insertCampsiteWorkTeacher(campsiteWorkTeacher));
    }

    /**
     * 修改【请填写功能名称】
     */
    // @PreAuthorize(hasPermi = "common:teacher:edit")
    @Log(title = "修改作业", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CampsiteWorkTeacher campsiteWorkTeacher) {
        /**编辑作业题目时候也不能添加相同的名字*/
        List<String> stringList = campsiteWorkTeacherService.ChaXunZuoYe(campsiteWorkTeacher.getCampId());
        if (stringList != null && campsiteWorkTeacher.getWorkName() != null) {
            for (String s : stringList) {
                if (campsiteWorkTeacher.getWorkName().equals(s)) {
                    return AjaxResult.error("作业名称不能相同");
                }
            }
        }
        /**设置自动修改时间*/
        Date date = new Date();
        campsiteWorkTeacher.setUpdateTime(date);
        return toAjax(campsiteWorkTeacherService.updateCampsiteWorkTeacher(campsiteWorkTeacher));
    }

    /**
     * 删除【请填写功能名称】
     */
    //  @PreAuthorize(hasPermi = "common:teacher:remove")
    @Log(title = "删除作业", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        /**删除作业之后必须将这次作业之后的其他作业的题号按顺序修改*/

        return toAjax(campsiteWorkTeacherService.deleteCampsiteWorkTeacherByIds(ids));
    }

    /**
     * 教师上传作业pdf,word,excel等文件，需要使用文件数组
     */
    @PostMapping("/UploadWork")
    public AjaxResult UploadWork(MultipartFile[] multipartFile) {
        /**用来装载这些url，多的之间使用,隔开*/
        List<String> list = new ArrayList<>();
        /**首先进行判空，老一套了*/
        if (multipartFile == null || multipartFile.length <= 0) {
            return AjaxResult.error("请不要上传空文件");
        }
        /**判断文件的大小不能超过十个*/
        if (multipartFile.length > 10) {
            return AjaxResult.error("请不要上传大于10个文件");
        }
        /**遍历文件进oss*/
        for (int i = 0; i < multipartFile.length; i++) {
            MultipartFile multipartFile1 = multipartFile[i];
            log.info("开始上传文件了");
            String originalFilename = multipartFile1.getOriginalFilename();
            String url;
            String s = UUID.randomUUID().toString().trim().replaceAll("-", "");
            String objectName = s + "work/" + originalFilename;
            String bucketName = "campiste-test";
            File file = new File("/mnt/upload/" + objectName);
            try {
                if (!file.exists()) {
                    file.mkdirs();
                }
                log.info("收到文件...");
                multipartFile1.transferTo(file);
                log.info("保存文件完毕...");
                ossClientInter.putObject(bucketName, objectName, file);
                url = "http://campiste.oss-cn-beijing.aliyuncs.com" + "/" + objectName;
                log.info("上传完毕...");
                list.add(url);
            } catch (Exception e) {
                e.printStackTrace();
                log.info("第" + i + "文件上传失败");
            } finally {
                file.delete();
            }
        }
        /**将所得的URL集合转换为大的字符串*/
        String join = StringUtils.join(list, ",");
        return AjaxResult.success(join);
    }

    @Log(title = "删除作业", businessType = BusinessType.DELETE)
    @PostMapping("/delete")
    /**作业的逻辑删除*/
    public AjaxResult WorkLd(@RequestParam(value = "campId") String campId,
                             @RequestParam(value = "id") Integer id) {
        campsiteWorkTeacherService.WorkLuoJi(campId, id);
        return AjaxResult.success("删除成功");
    }

    @Log(title = "修改作业2", businessType = BusinessType.UPDATE)
    /**修改作业的新街口*/
    @PostMapping("/Update")
    public AjaxResult Update(@RequestBody CampsiteWorkTeacher campsiteWorkTeacher) {
        /**编辑作业题目时候也不能添加相同的名字*/
        List<String> stringList = campsiteWorkTeacherService.ChaXunZuoYe(campsiteWorkTeacher.getCampId());
        /**查询此次作业名称(修改的时候把自己去掉)*/
        String s1 = campsiteWorkTeacherService.DanGeZuoYe(campsiteWorkTeacher.getId());
        /**如果这个营地的总题号包含这个题目名称就把它去除掉，当然是肯定包含的*/
        if (stringList.contains(s1)) {
            /**把自己的题号去除，然后遍历剩下的元素，如果发现是一样的，就提示不能一样*/
            List<String> collect = stringList.stream().filter(x -> !x.equals(s1)).collect(Collectors.toList());
            if (collect != null && campsiteWorkTeacher.getWorkName() != null) {
                for (String s : collect) {
                    if (campsiteWorkTeacher.getWorkName().equals(s)) {
                        return AjaxResult.error("作业名称不能相同");
                    }
                }
            }
        }

        int i = campsiteWorkTeacherService.updateCampsiteWorkTeacher(campsiteWorkTeacher);
        return AjaxResult.success("编辑作业成功");
    }

    @Log(title = "删除作业2", businessType = BusinessType.DELETE)
    @PostMapping("/NewDelete")
    public AjaxResult NewDelete(@RequestBody CampsiteWorkTeacher campsiteWorkTeacher) {
        /**删除之前必须判断这个作业有没有人提交过
         * 如果有人提交则不能删除*/
        String s = campsiteWorkTeacherService.IsStudentTiJiao(campsiteWorkTeacher.getId());
        if (s == null) {
            /**删除此次作业之后必须将这次作业之后的题号按顺序修改*/
            /**首先查询当前营地下面的所有作业名称，这个是唯一的*/
            List<String> stringList = campsiteWorkTeacherService.ChaXunZuoYe(campsiteWorkTeacher.getCampId());
            /**如果原来的集合就是1个的话直接删除*/
            if (stringList.size() == 1) {
                campsiteWorkTeacherService.deleteCampsiteWorkTeacherById(campsiteWorkTeacher.getId());
                return AjaxResult.success("删除成功");
            }
            /**再次找到这个题目名在这个集合的位置*/
            int i = stringList.indexOf(campsiteWorkTeacher.getWorkName());
            /**如果这题是最后一个也是直接删*/
            int ld = i + 1;
            if (ld == stringList.size()) {
                campsiteWorkTeacherService.deleteCampsiteWorkTeacherById(campsiteWorkTeacher.getId());
                return AjaxResult.success("删除成功");
            }
            /**将这个题目下面的所有题目的题号减一。加入数据库*/
            for (int a = i; a < stringList.size() - 1; a++) {
                /**获取当前题目的下一题的题目名*/
                String workname = stringList.get(a + 1);
                /**获取需要删除的题目也就是当前题目的下一题的题号*/
                Integer worknumber = a + 1;
                campsiteWorkTeacherService.XiuGaiZuoYeTiHao(worknumber, workname, campsiteWorkTeacher.getCampId());
            }
            /**然后再执行删除*/
            campsiteWorkTeacherService.deleteCampsiteWorkTeacherById(campsiteWorkTeacher.getId());
            return AjaxResult.success("删除成功");
        } else {
            return AjaxResult.error("此次作业已经有学生提交了，不可删除");
        }
    }

    @GetMapping("/zipStuAnswer")
    public AjaxResult zipStuAnswer(@RequestParam("studentId") String studentId, @RequestParam("campId") String campId) {
        String urls = campsiteWorkTeacherService.getStuEnclosUrl(studentId, campId);
        if (StringUtils.isEmpty(urls)) {
            return AjaxResult.error("没有文件");
        }
        String[] urlArray = urls.split(",");
        /**将文件名改为雪生的姓名*/
        String s1 = campsiteWorkTeacherService.SelectByIdUuid(studentId);
        File fileZip = new File("D:/mnt/" + campId + "/" + s1 + ".zip");
        try {
            String baseUrl = "https://campiste.oss-cn-beijing.aliyuncs.com/studentwork/" + campId + "/" + studentId + "/work/";
            for (String s : urlArray) {
                String fileName = s.replace(baseUrl, "");
                GetObjectRequest getObjectRequest = new GetObjectRequest("campiste", "studentwork/" + campId + "/" + studentId + "/work/" + fileName);
                File file = new File("D:/mnt/" + campId + "/" + s1 + "/" + fileName);
                if (!file.getParentFile().isDirectory()) {
                    file.getParentFile().mkdirs();
                }
                //下载文件
                ossClientInter.getObject(getObjectRequest, file);
            }
            ZipUtil.zip("D:/mnt/" + campId + "/" + s1 + "/", "D:/mnt/" + campId + "/" + s1 + ".zip");
            ossClientInter.putObject("campiste", "studentwork/zip/" + studentId + "/" + fileZip.getName(), fileZip);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileZip.exists()) {
                fileZip.delete();
                File file = new File("D:/mnt/" + campId + "/" + s1);
                if (file.exists()) {
                    File[] files = file.listFiles();
                    for (File file1 : files) {
                        file1.delete();
                    }
                    file.delete();
                }
            }
        }
        return AjaxResult.success("正在排队中，如果无文件请稍后再试，请稍后在访问连接", "https://campiste.oss-cn-beijing.aliyuncs.com/studentwork/zip/" + studentId + "/" + fileZip.getName());
    }

}
